const state = () => ({
  roles: {
    developer: ['submit_package', 'view_submissions'],
    reviewer: ['review_package', 'reject_submission'],
    admin: ['manage_users', 'audit_logs']
  },
  currentRole: 'developer'
})

const getters = {
  availableActions: (state) => state.roles[state.currentRole] || []
}

const mutations = {
  SET_ROLE(state, role) {
    if (Object.keys(state.roles).includes(role)) {
      state.currentRole = role
    }
  },
  UPDATE_PERMISSIONS(state, { role, permissions }) {
    state.roles[role] = [...new Set(permissions)]
  }
}

const actions = {
  async syncPermissions({ commit }) {
    try {
      const response = await fetch('/api/permissions')
      const data = await response.json()
      commit('UPDATE_PERMISSIONS', data)
    } catch (error) {
      console.error('权限同步失败:', error)
    }
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}